package com.interest.controller.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.interest.authorization.manager.impl.RedisTokenManager;
import com.interest.base.common.Constants;
import com.interest.base.entity.ModelBean;
import com.interest.execshell.CommandHelper;
import com.interest.execshell.CommandResult;
import com.interest.modules.account.service.AccountService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;

/**
 * 登陆控制器
 *
 * @author wangliang
 */
@Controller
@RequestMapping("/api")
public class ApiMainThemesController {
    private static Logger logger = Logger.getLogger(ApiMainThemesController.class);
    @Autowired
    private AccountService accountService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @RequestMapping(value = "/theme", method = RequestMethod.GET)
    @ResponseBody
    public ModelBean getTheme(@RequestParam(value = "type", required = true) String themeType) {
        if (themeType == null || themeType.length() == 0) {
            return new ModelBean(Constants.STATUS_ERROR, "error");
        } else if ("main".equals(themeType)) {
            JSONArray themeArray = new JSONArray();
            JSONObject theme1 = new JSONObject();
            theme1.put("themeUrl", "http://www.apkui.com/zb_users/thumbimg/2015/06/201506269441_3603.png");
            theme1.put("themeDes", "侧边栏");
            theme1.put("themeType", 0);
            themeArray.add(theme1);

            JSONObject theme2 = new JSONObject();
            theme2.put("themeUrl", "http://img0.pconline.com" +
                    ".cn/pconline/1505/13/6453336_Screenshot_2015-05-13-11-02-29_thumb.png");
            theme2.put("themeDes", "底部标签");
            theme2.put("themeType", 1);
            themeArray.add(theme2);
            JSONObject data = new JSONObject();
            data.put("themeArray", themeArray);
            return new ModelBean(data);
        } else {
            return new ModelBean(Constants.STATUS_ERROR, "error");
        }
    }


    @RequestMapping(value = "/autoApp", method = RequestMethod.POST)
    @ResponseBody
    public ModelBean autoApp(@RequestBody String configs) {
        if (configs == null || configs.length() == 0) {
            return new ModelBean("配置为空");
        } else {
            String confPath = "/autoapp/files/editConfigs";
            JSONObject data = new JSONObject();
            File editConfig = new File(configs);
            if (!editConfig.exists()) {
                //如果文件不存在创建文件
                editConfig.mkdir();
            }
            try {
                FileOutputStream fos = new FileOutputStream(confPath);
                fos.write(configs.getBytes());
                fos.close();

                try {
                    CommandHelper.DEFAULT_TIMEOUT = 60000;
                    CommandResult result = CommandHelper.exec("bash /autoapp/shell/autoapp_rungo.sh ");
                    if (result != null) {
                        logger.info("output: " + result.getOutput() + "\n Error: " + result.getError());
                    }
                    return new ModelBean(data);

                } catch (IOException ex) {
                    logger.info("IOException: " + ex.getLocalizedMessage());
                    return new ModelBean("IO异常　执行命令出错");
                } catch (InterruptedException ex) {
                    logger.info("InterruptedException: " + ex.getLocalizedMessage());
                    return new ModelBean("Interrupted异常　执行命令出错");
                }


            } catch (Exception e) {
                logger.info("Exception: " + e.getLocalizedMessage());
                return new ModelBean("写入配置出错");
            }
        }
    }


    /*
            *采用spring提供的上传文件的方法
    */
    @RequestMapping("springUpload")
    @ResponseBody
    public ModelBean springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
        long startTime = System.currentTimeMillis();
        String filePath = request.getServletContext().getRealPath("/") + "files/";
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdir();
        }

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        JSONArray files = new JSONArray();
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();


            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    logger.info("origin filename >> " + myFileName);

                    if (myFileName.trim() != "") {
                        //重命名上传后的文件名
                        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
                        if (myFileName.contains(".")) {
                            String[] arr = myFileName.split("\\.");
                            fileName += ".";
                            fileName += arr[arr.length - 1];
                        }
                        //定义上传路径
                        String path = filePath + fileName;
                        logger.info("file save path >> " + path);
                        File localFile = new File(path);
                        try {
                            file.transferTo(localFile);
                        } catch (IOException e) {
                            logger.info("upload file io exception.");
                            e.printStackTrace();
                        }
                        files.add(path);
                    }
                    //String path = "/home/luoxf/develop/autoappserver/uploadFiles/" + file.getOriginalFilename();
                    //上传
                    //file.transferTo(new File(path));
                }
            }

        }
        long endTime = System.currentTimeMillis();
        System.out.println("运行时间：" + String.valueOf(endTime - startTime) + "ms");
        JSONObject data = new JSONObject();
        data.put("result", "上传成功");
        data.put("files", files);
        return new ModelBean(data);
    }

}
